<template>
  <a-modal
      title="创建模板"
      v-model:visible="visible"
      :confirm-loading="confirmLoading"
      :afterClose="remove"
      :width="720"
      :bodyStyle="{maxHeight: '640px', overflow: 'auto'}"
      @ok="handleOk"
  >
    <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="模板名称">
        <a-input v-model:value="templatename" placeholder="模板名称"/>
      </a-form-item>
<!--      <a-form-item label="添加方式">-->
<!--        <a-radio-group v-model:value="addType">-->
<!--          <a-radio :value="1">-->
<!--            手动添加-->
<!--          </a-radio>-->
<!--          <a-radio :value="2">-->
<!--            自动学习-->
<!--          </a-radio>-->
<!--        </a-radio-group>-->
<!--      </a-form-item>-->
<!--      <a-form-item label="系统类型">-->
<!--        <a-radio-group v-model:value="systemType">-->
<!--          <a-radio :value="1">-->
<!--            Windows-->
<!--          </a-radio>-->
<!--          <a-radio :value="2">-->
<!--            Linux-->
<!--          </a-radio>-->
<!--        </a-radio-group>-->
<!--      </a-form-item>-->
<!--      <template v-if="addType == 2">-->
<!--        <a-form-item label="部门">-->
<!--          <a-tree-select-->
<!--              ref="treeSelectRef"-->
<!--              v-model:value="departmentid"-->
<!--              tree-data-simple-mode-->
<!--              style="width: 100%"-->
<!--              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"-->
<!--              :tree-data="treeData"-->
<!--              placeholder="请选择部门"-->
<!--              @change="treeSelect"-->
<!--          />-->
<!--        </a-form-item>-->
<!--        <a-form-item label="要学习的客户端">-->
<!--          <a-select-->
<!--              v-model:value="clientid"-->
<!--              @change="selectClient"-->
<!--          >-->
<!--            <Option v-for="item in clientList" :value="item.id" :key="item.id">-->
<!--              {{ item.clientname }}-->
<!--            </Option>-->
<!--          </a-select>-->
<!--        </a-form-item>-->
<!--      </template>-->
      <a-form-item v-for="(formItem, key, index) in formItems" :label="formItem.label" :key="key">
        <template v-if="formItem.single">
          <a-select
            v-model:value="formItem.value.id"
            :placeholder="formItem.placeholder"
            option-label-prop="label"
          >
            <a-select-option key="" value="" label="无">无</a-select-option>
            <a-select-option v-for="i in buffer[key]" :key="i.id" :value="i.id" :label="i.name">
              {{i.name}}
            </a-select-option>
          </a-select>
        </template>
        <template v-else>
        <a-tag v-for="item in formItem.value" closable @close="closeTag({key, id: item.id})" :color="tagColors[index]" :key="item.id">
          {{ item.name }}
        </a-tag>
        <a-button @click="selectStrategy({formItem,key})" size="small" type="primary">选择</a-button>
        </template>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import {defineComponent, reactive, toRefs, ref} from 'vue'
import {Modal, Form, Button, Radio,Select,TreeSelect, Tag, Input, message} from 'ant-design-vue'
import DynamicTable from '@/components/dynamic-table.vue'
import SelectModal from "./select-modal.vue"
import {useCreateModal} from "@/hooks"
import {formItems} from './formItems'
import {strategyTableProp} from './strategyTableProp'
import {cloneDeep, unionWith, isEqual} from 'lodash'
import {templateCreate, templateUpdate} from '@/api/strategy/template'

const tagColors = [ "blue", "cyan", "gold", "lime", "magenta", "orange", "pink", "purple", "red", "yellow", "error", "success", "warning", "processing", "geekblue", "volcano",]

export default defineComponent({
  name: "add-modal",
  components: {
    [Modal.name]: Modal,
    [Form.name]: Form,
    [Radio.Group.name]: Radio.Group,
    [Radio.name]: Radio,
    [Input.name]: Input,
    [Select.name]: Select,
    [TreeSelect.name]: TreeSelect,
    "a-select-option": Select.Option,
    [Form.Item.name]: Form.Item,
    [Button.name]: Button,
    [Tag.name]: Tag,
    DynamicTable
  },
  props: {
    remove: { // 移除模态框
      type: Function
    },
    operateType: {
      type: String,
      validator: (val: string) => ['add', 'edit'].includes(val)
    },
    fields: {
      type: Object,
      default: () => ({})
    },
    callback: {
      type: Function
    }
  },
  setup(props) {
    const treeSelectRef = ref<any>(null)

    const state = reactive({
      visible: true,
      confirmLoading: false,
      templatename: props.fields.templatename || '',
      // clientid: undefined, // 要学习的客户端
      // clientList: [] as any[], // 客户端列表
      // departmentid: undefined, // 部门id
      // treeData: [] as any, // 树形数据
      systemType: 1, // 系统类型
      addType: 1, // 添加方式
      formItems: cloneDeep(formItems),
      backUp:cloneDeep(formItems),
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          state.rowSelection.selectedRowKeys = selectedRowKeys
        },
        selectedRowKeys: []
      },
      buffer:{}
    })

    Object.keys(formItems).forEach(key => {
      const keys = props.fields[formItems[key].key]?.split(',') || []
      const names = props.fields[formItems[key].name]?.split(',') || []
      if(!formItems[key].single){
        state.formItems[key].value = keys.map((id, index) => ({
          id: id,
          name: names[index]
        }))
      }else{
        state.buffer[key]=keys.map((id,index)=>({
          id:id,
          name: names[index]
        }))
      }
    })

    ~ async function(){
      Object.keys(formItems).forEach(key =>{
        // const data = formItems[key]?.source(props.fields.id) || []
        // data.then((data)=> {
        //   Object.keys(data).forEach(i => {
        //     if(formItems[key].single){
        //       state.formItems[key].value= {id:data[i][strategyTableProp[key].rowKey]}
        //       state.backUp[key].value= {id:data[i][strategyTableProp[key].rowKey]}
        //     }else {
        //       state.formItems[key].value.push({id: data[i][strategyTableProp[key].rowKey], name: data[i]['name']})
        //       state.backUp[key].value.push({id: data[i][strategyTableProp[key].rowKey], name: data[i]['name']})
        //     }
        //   })
        // })
        if(formItems[key].single){
          const prop = strategyTableProp[key]
          prop.func({page:1,limit:1000,...prop.pageOption}).then(
              res => {
                Object.keys(res.data).forEach(i=>{
                  state.buffer[key].push({id:res.data[i][strategyTableProp[key].rowKey],name:res.data[i]['name']})
                })
              }
          )
        }
      })
    }()

    // 选择策略
    const selectStrategy = ({formItem, key}) => {
      console.log(formItem, key)
      if(!formItem.single){
        useCreateModal(SelectModal, {
          title: formItem.label,
          strategyType: key,
          callback: (strategyType, selected) => {
            const newArr = selected.map(item => ({
              id: item[strategyTableProp[strategyType].rowKey],
              name: item[strategyTableProp[strategyType].rowName]
            }))
            state.formItems[key].value = unionWith(state.formItems[key].value, newArr, isEqual)
          }
        })
      }

    }

    // // 获取部门树
    // const getDeptTree = async (fatherId: string | number) => {
    //   const param = {
    //     ID: fatherId
    //   }
    //   const {data} = await deptAll(param)
    //   return data.map(item => ({
    //     id: item.departmentid,
    //     pId: item.parent,
    //     value: item.departmentid,
    //     title: item.name
    //   }))
    // }
    //
    // // 初始化树
    // const initDeptTree = async () => {
    //   const data = await deptSelectbyName({name: 'root'})
    //   state.treeData = await getDeptTree(data.departmentid)
    //   console.log(state.treeData, '树据')
    // }
    // initDeptTree()
    //
    // // 选择部门
    // const treeSelect = async (value,node,extra) => {
    //   const {data} = await clientGetByDepartment({departmentid: value, limit: 200})
    //   state.clientList = data
    //   state.clientid = undefined
    //   let currentNode = extra.triggerNode
    //   let str = ''
    //   while (currentNode.dataRef.pId != 0) {
    //     str += currentNode.title + ' / '
    //     currentNode = currentNode.vcTreeNode
    //   }
    //   str += currentNode.title
    //   treeSelectRef.value.$el.parentElement.querySelector('.ant-select-selection-item').textContent = str.split(' / ').reverse().join(' / ')
    // }
    //
    // // 选择客户端
    // const selectClient = async (value) => {
    //   const data = await clientTemplate({clientId: value})
    //   Object.keys(formItems).forEach(key => {
    //     const keys = data[formItems[key].key]?.split(',') || []
    //     const names = data[formItems[key].name]?.split(',') || []
    //     state.formItems[key].value = keys.map((id, index) => ({
    //       id: id,
    //       name: names[index]
    //     }))
    //   })
    // }

    // 关闭标签
    const closeTag = ({key, id}) => {
      state.formItems[key].value = state.formItems[key].value.filter(item => item.id != id)
    }

    const getIds = (key): string[] => {
      console.log(key,state.formItems[key].value)
      if(formItems[key].single){
        return state.formItems[key].value.id
      }else{
        return state.formItems[key].value.map((item: any) => item.id)
      }
    }

    const compare = (a: any,b: any) => {
      if(a.length != b.length) {return false}
      let find=false
      for(const i in a) {
        find = false
        for (const j in b) {
          if (a[i]['id'] == b[j]['id']) {find = true}
        }
        if(!find) {return false}
      }
      return true
    }

    const handleOk = async () => {
      if (state.templatename.trim() == '') return message.warning('模板名称不能为空！')
      state.confirmLoading = true
      const template = {
        templatename: state.templatename,
        global: 0
      }
      await templateCreate(template).then(res=>{
        if(0==res['code']){
          const params={
            tempid: res["data"],
            whiteids: getIds('whiteList'),
            blackids: getIds('blackList'),
            portids: getIds('portManagement'),
            docids: getIds('docControl').concat(getIds('docOut')),
            inboundids: getIds('firewall'),
            outboundids: getIds('firewallout'),
            cipherids: new Array<string>().concat(getIds('cipher')),
          }
          Object.keys(formItems).forEach(key=>{
            if(formItems[key].single){
              if((null!=formItems[key].update)&&(state.formItems[key].value.id!=state.backUp[key].value.id)){
                formItems[key].update(params)
              }
            }else{
              if((null!=formItems[key].update)&&(!compare(state.formItems[key].value,state.backUp[key].value))){
                formItems[key].update(params)
              }
            }

          })
        }
      })

      props.callback && props.callback()
      state.visible = false
    }

    return {
      ...toRefs(state),
      treeSelectRef,
      tagColors,
      handleOk,
      strategyTableProp,
      // selectClient,
      // treeSelect,
      selectStrategy,
      closeTag,
      labelCol: {span: 6},
      wrapperCol: {span: 18}
    }
  }
})
</script>

<style lang="scss" scoped>
</style>
